package com.jaws.demo.common.batch;

import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;


/**
 * CVS 数据校验
 *
 * @author liangqm
 * @date 2018-04-19 8:22:17
 * @since v1.0.1
 */
public class CsvBeanValidator<T> implements Validator<T>, InitializingBean {
	private javax.validation.Validator validator;

	/**
	 * 使用Validator的validate方法校验数据
	 *
	 * @author liangqm
	 * @date 2018-04-24 15:35:18
	 * @params value
	 * @since v1.0.1
	 */
	@Override
	public void validate(T value) throws ValidationException {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(value);
		if (constraintViolations.size() > 0) {
			StringBuilder message = new StringBuilder();
			for (ConstraintViolation<T> constraintViolation : constraintViolations) {
				message.append(constraintViolation.getMessage() + "\n");
			}
			throw new ValidationException(message.toString());
		}
	}

	/**
	 * 使用JSR-303的Validator来校验我们的数据，在此进行JSR-303的Validator的初始化
	 *
	 * @author liangqm
	 * @date 2018-04-24 15:35:17
	 * @params
	 * @since v1.0.1
	 */
	@Override
	public void afterPropertiesSet() {
		ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
		validator = validatorFactory.usingContext().getValidator();
	}
}  